package com.sgb.kjwl.view.ui.activity.chat;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtNewsNotcieViewBinding;
import com.sgb.kjwl.model.entity.chat.NewsMenuEntity;
import com.sgb.kjwl.view.ui.adapter.NewsPagerAdapter;
import com.sgb.kjwl.view.ui.fragment.chat.NewsNoticeFragment;
import com.sgb.kjwl.view.widget.TitlePopWindow;
import com.sgb.kjwl.viewmodel.chat.NewsNoticeModel;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.view.entity.ChannelEntity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 新通知界面
 * Create by LiWei 2021/11/14
 */
@Route(path = "/jyb_im/news_notice")
public class NewsNoticeActivity extends AppActivity {

    private AtNewsNotcieViewBinding binding;
    private NewsNoticeModel viewModel;
    private TitlePopWindow titlePopWindow;

    private List<NewsMenuEntity> newEntities;
    private List<NewsMenuEntity> changeNoticeList; //排序后数据源

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ContactBookActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(NewsNoticeActivity.this, R.layout.at_news_notcie_view);
        viewModel = new ViewModelProvider(this).get(NewsNoticeModel.class);
        binding.include.titleView.setText("通知");
        binding.include.ivBack.setOnClickListener(this);
        binding.ivShowMore.setOnClickListener(this);

        viewModel.noticeMenuList.observe(this, new Observer<List<NewsMenuEntity>>() {
            @Override
            public void onChanged(List<NewsMenuEntity> newsMenuEntities) {
                //handleMenuData(newsMenuEntities);
                initTabMenu(newsMenuEntities);
            }
        });

        String timelineId = MkvUtils.get().getString(MkvUtils.get().CacheUserCenterMenu, CacheMarker.IM_NOTICE_TIME_ID, "");
        if (TextUtils.isEmpty(timelineId))
            return;
        //初始化菜单界面
        viewModel.getNoticeMenuList(timelineId, "2");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_show_more:
                showTitlePopWindow();
                break;
        }
    }

    /**
     * 处理数据是否有缓存处理
     *
     * @param list 接口返回的数据
     */
    private void handleMenuData(List<NewsMenuEntity> list) {
        if (list.size() == 0) {
            binding.linTab.setVisibility(View.GONE);
            binding.emptyView.setVisibility(View.VISIBLE);
            return;
        }
        newEntities = new ArrayList<>();
        Type type = new TypeToken<List<NewsMenuEntity>>() {
        }.getType();
        Object object = DatalUtils.getInstance().getData(MkvUtils.CommomData, CacheMarker.IM_SORT_DATA, type);
        if (object != null) {
            //缓存数据
            List<NewsMenuEntity> cacheList = (List<NewsMenuEntity>) object;
            //用来处理是否含有新增数据
            List<NewsMenuEntity> newAddList = new ArrayList<>();
            newAddList.addAll(list);
            //处理后生成的新的菜单数据
            List<NewsMenuEntity> newList = new ArrayList<>();
            for (NewsMenuEntity entity : cacheList) {
                for (NewsMenuEntity menuEntity : list) {
                    if (entity.getType().equals(menuEntity.getType())) {
                        newList.add(menuEntity);
                        newAddList.remove(menuEntity);
                    }
                }
            }
            newList.addAll(newAddList);
            newEntities.addAll(newList);
            initTabMenu(newList);
        } else {
            newEntities.addAll(list);
            initTabMenu(list);
        }
    }

    private void initTabMenu(List<NewsMenuEntity> list) {
        if (list.size() == 0) {
            binding.linTab.setVisibility(View.GONE);
            binding.emptyView.setVisibility(View.VISIBLE);
            return;
        }
        newEntities = new ArrayList<>();
        newEntities.addAll(list);
        binding.tabLayout.clearOnTabSelectedListeners();
        binding.tabLayout.removeAllTabs();
        List<Fragment> fragmentList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            fragmentList.add(NewsNoticeFragment.newInstance(list.get(i).getType()));
        }
        NewsPagerAdapter adapter = new NewsPagerAdapter(getSupportFragmentManager(), fragmentList, list);
        binding.viewPager.setAdapter(adapter);
        binding.tabLayout.setupWithViewPager(binding.viewPager);
        binding.viewPager.setOffscreenPageLimit(1);
        binding.viewPager.setCurrentItem(0);
        for (int i = 0; i < fragmentList.size(); i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_tab_news_menu, null, false);
            binding.tabLayout.getTabAt(i).setCustomView(view);
            TextView tv = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_name);
            TextView tvUnReadNum = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_unReadNum);
            tv.setText(list.get(i).getName());
            if (list.get(i).getUnReadNum() != 0) {
                tvUnReadNum.setText(list.get(i).getUnReadNum() + "");
                tvUnReadNum.setVisibility(View.VISIBLE);
            } else {
                tvUnReadNum.setVisibility(View.GONE);
            }
            if (i == 0) {
                tv.setSelected(true);
                tvUnReadNum.setVisibility(View.GONE);
            }
        }
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_name);
                TextView tvUnReadNum = tab.getCustomView().findViewById(R.id.tv_unReadNum);
                tv.setSelected(true);
                tvUnReadNum.setVisibility(View.GONE);
                tv.invalidate();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_name);
                tv.setSelected(false);
                tv.invalidate();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /*
     * 展示可排序操作界面
     */
    private void showTitlePopWindow() {
        if (titlePopWindow == null) {
            List<ChannelEntity> list = new ArrayList<>();
            for (NewsMenuEntity newEntity : newEntities) {
                ChannelEntity entity = new ChannelEntity();
                entity.setName(newEntity.getName());
                entity.setSort(newEntity.getType());
                list.add(entity);
            }
            titlePopWindow = new TitlePopWindow(this, list);
            titlePopWindow.setTitle("通知类型管理");
            titlePopWindow.setBgView(binding.grayLayout);
            titlePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
                @Override
                public void disMiss() {
                    if (!titlePopWindow.isShowing()) {
                        //binding.ivShowMore.setRotation(0);
                    }
                }
            });
            titlePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    List<ChannelEntity> channelEntityList = (List<ChannelEntity>) key1;
                    List<String> sortData = new ArrayList<>();
                    if (changeNoticeList == null)
                        changeNoticeList = new ArrayList<>();
                    changeNoticeList.clear();
                    for (ChannelEntity entity : channelEntityList) {
                        sortData.add(entity.getSort());
                        for (NewsMenuEntity newEntity : newEntities) {
                            if (TextUtils.equals(entity.getSort(), newEntity.getType())) {
                                changeNoticeList.add(newEntity);
                                continue;
                            }
                        }
                    }
                    String timelineId = MkvUtils.get().getString(MkvUtils.get().CacheUserCenterMenu, CacheMarker.IM_NOTICE_TIME_ID, "");
                    if (TextUtils.isEmpty(timelineId))
                        return;
                    viewModel.uploadNoticeSortList(timelineId, sortData);
                    //DatalUtils.getInstance().putData(MkvUtils.CommomData, CacheMarker.IM_SORT_DATA, changeNoticeList);
                    //initTabMenu(changeNoticeList);
                }
            });
        } else {
            titlePopWindow.showPopwindow0(binding.linTab);
            // binding.ivShowMore.setRotation(180);
        }
    }
}
